package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.Constants;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.SendSmsUtil;
import com.zhisuo.apicenter.util.StringUtil;
import com.zhisuo.apicenter.util.TcpUtil;
import com.zhisuo.apicenter.util.TimeUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;


/**
 * 用户相关操作
 */
@Controller
@RequestMapping(value = "/userman")
public class UserManController {

    private static final Logger log = LoggerFactory.getLogger(UserManController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private ExpressManService expressManService;
    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }


    private UserManService userManService;
    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }

    /**
     * 根据单号实时获取收件用户手册号
     */
    @RequestMapping(value = "/getReceiptMobileByTransferCode")
    public void getReceiptMobileByTransferCode(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptMobileByTransferCode-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String transfercode = jsonObject.getString("transfercode");







    }
        /**
         * 用户一键代取
         */
    @RequestMapping(value = "/setAllReceiptOrderByOtherUserId")
    public void setAllReceiptOrderByOtherUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setAllReceiptOrderByOtherUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String giveusermobile = jsonObject.getString("giveusermobile");


        ZhiSuoUser user=userManService.getZhiSuoUserById(userid);
        //获取用户未预约订单
        List<DeliveryOrder> listDeliveryOrder=userManService.getListDeliveryNoOrderByReceiptMobile(user.getMobile());
        if(listDeliveryOrder != null && listDeliveryOrder.size()>0){
            for(DeliveryOrder order:listDeliveryOrder){
              //修改订单，赋予他人
                userManService.updateDeliveryOrderGiveOtherUserByStatus(order.getId(),giveusermobile,order.getReceiptusermobile());


            }
        }else{
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "无订单可给予");
            responseData(resultObj.toString(), resp);
            return;
        }

        //发送短信
        String[] phoneNumbers = new String[]{giveusermobile};
        String smsjson = SendSmsUtil.sendSmsPutBox(phoneNumbers);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "给予成功");
        responseData(resultObj.toString(), resp);
    }

    /**
     * 用户一键预约
     */
    @RequestMapping(value = "/setAllReceiptOrderByUserId")
    public void setAllReceiptOrderByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setAllReceiptOrderByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String buildid = jsonObject.getString("buildid");
        String receiptuserorderstarttime = jsonObject.getString("receiptuserorderstarttime");
        String receiptuserorderendtime = jsonObject.getString("receiptuserorderendtime");


        //查询当前时间段有几单
        List<Integer> count=userManService.getDeliveryOrderCountByOrderTime(receiptuserorderstarttime,receiptuserorderendtime);
        if(count != null){
            if(count.size()>=5){
                responseErrorData("该时间段预约订单超量，请重新选择时间段", resp);
                return;
            }
        }

        //获取用户默认地址
//        ZhiSuoUserAddress userAddress=userManService.getZhisuoFlagUserAddressByUserId(Integer.parseInt(userid));
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(Integer.parseInt(buildid));

        ZhiSuoUser user=userManService.getZhiSuoUserById(userid);
        //获取用户未预约订单
        List<DeliveryOrder> listDeliveryOrder=userManService.getListDeliveryNoOrderByReceiptMobile(user.getMobile());
        Integer hasrnum=0;
        Integer hasnonum=0;
        if(listDeliveryOrder != null && listDeliveryOrder.size()>0){
            for(DeliveryOrder order:listDeliveryOrder){
                //查看订单车辆所在区域
                String parkareaid=userManService.getParkAreaIdByCarId(order.getCarid());
                if(parkareaid.equals(buildinfo.getParkareaid()+"")){
                    String receiptcode= RandomStringUtils.random(4, "1234567890");
                    userManService.updateReceiptOrderSysTimeStatusByBuildId(order.getId()+"",receiptcode,buildinfo.getCode(),buildinfo.getId(),receiptuserorderstarttime,receiptuserorderendtime);
                    hasrnum=hasrnum+1;
                }else{
                    hasnonum=hasnonum+1;
                }
            }
        }else{
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "无订单可预约");
            responseData(resultObj.toString(), resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "您已成功自动预约"+hasrnum+"件"+",未成功预约"+hasnonum+"件");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 用户寄件数量查询接口
     */
    @RequestMapping(value = "/getSendOrderNumByUserId")
    public void getSendOrderNumByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSendOrderNumByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        ZhiSuoUser user = userManService.getZhiSuoUserById(userid);

        Integer orderhasreciptnum=0;
        orderhasreciptnum =userManService.getHasSendOrderNumByUserId(user.getMobile());
        JSONObject datajson=new JSONObject();
        datajson.put("orderhasreciptnum",orderhasreciptnum);
        resultObj.put("error_code",0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data",datajson);
        responseData(resultObj.toString(), resp);

    }





    /**
         * 用户首页获取收件数量
         */
    @RequestMapping(value = "/getReceiptOrderNumByUserId")
    public void getReceiptOrderNumByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderNumByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        ZhiSuoUser user=userManService.getZhiSuoUserById(userid);

        Integer orderhasreciptnum=0;
        Integer orderhasorder=0;
        Integer sellerorderhasreciptnum=0;
        Integer sellerorderhasorder=0;

        //快递待取件
        orderhasreciptnum=userManService.getHasOrderNumByUserId(user.getMobile(),0);
        //零售待取件
        sellerorderhasreciptnum=userManService.getHasOrderNumByUserId(user.getMobile(),1);
        //快递待预约
        orderhasorder=userManService.getHasOrderNumByUserId(user.getMobile(),2);
        //零售待预约
        sellerorderhasorder=userManService.getHasOrderNumByUserId(user.getMobile(),3);
        JSONObject datajson=new JSONObject();
        datajson.put("orderhasreciptnum",orderhasreciptnum);
        datajson.put("orderhasorder",orderhasorder);
        datajson.put("sellerorderhasreciptnum",sellerorderhasreciptnum);
        datajson.put("sellerorderhasorder",sellerorderhasorder);
        resultObj.put("error_code",0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data",datajson);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 用户扫码取件
     */
    @RequestMapping(value = "/getReceiptOrderByCarIdId")
    public void getReceiptOrderByCarIdId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderByCarIdId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String sn = jsonObject.getString("sn");

        String mobile=userManService.getMobilByUserId(userid);
        ZhiSuoCar car=expressManService.getCarByQrcode(sn);

        if(car==null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "二维码已失效，请重新扫码");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        List<DeliveryOrder> listorder=userManService.getOrderIdByCarIdAndMobile(car.getId()+"",mobile);

        if(listorder != null && listorder.size()>0 ){


            //直接打开门
            //获取TCP服务器地址
            String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
            //下发开箱指令
            List<ZhiSuoCarBox> listZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(car.getId()+"");
            String tcpresult= TcpUtil.openManyDoor(car,listorder,listZhiSuoCarBox,tcp_url);

            if(StringUtils.isNotEmpty(tcpresult)){
                JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
                String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
                if(tcpresultjsonerrorCode.equals("1")){
                    responseErrorData("开门失败，请再试一次", resp);
                    return;
                }
            }


            JSONObject oneboxjson=null;
            JSONArray opendoorarray=new JSONArray();
            for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
                oneboxjson=new JSONObject();
                Boolean flag=false;
                for(DeliveryOrder order:listorder){
                    if(order.getBoxcode().equals(carbox.getName())){
                        flag=true;
                        break;
                    }else{
                        flag=false;
                    }
                }

                if(flag){
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","1");
                    oneboxjson.put("pos",carbox.getPos());
                }else{

                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","0");
                    oneboxjson.put("pos",carbox.getPos());
                }
                opendoorarray.add(oneboxjson);
            }




            for(DeliveryOrder order:listorder){

                userManService.updateOrderByReceiptcode(order.getId()+"",userid);
                //更新箱子状态
                expressManService.updateCarBoxStatusByCode(order.getBoxcode(),order.getCarid()+"");
                //增加积分
                if(order.getOrdertype()==0){
                    //只要零售单才会增加积分
                    Integer award_integral=apiService.getAwardIntegeralByConfig("award_integral");
                    //用户增加积分
                    userManService.updateUserIntegralByUserId(userid,award_integral);
                    //增加积分记录
                    userManService.insertNewZhiSuoUserIntegralRecord(userid,order.getId(),award_integral,0,0);
                }
            }


            //下发发车指令
            String nextstop=userManService.getNextStopByCarId(car.getId());
            String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
            //判断当前站点包裹是否取完
            ZhiSuoCarStatus carstatus = expressManService.getCarStatusByCarVin(car.getSn());



            if(StringUtils.isEmpty(nextstop)){
                if(carstatus==null){
                    carstatus=new ZhiSuoCarStatus();
                    carstatus.setPositionstop("");
                }
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),car.getHomestation(),stop_timeout_sec,carstatus.getPositionstop());
                System.out.println("saomaqujian---vin--"+car.getSn()+"--stop----"+car.getHomestation()+"---"+new Date());

            }else{
                if(carstatus==null){
                    carstatus=new ZhiSuoCarStatus();
                    carstatus.setPositionstop("");
                }
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop_timeout_sec,carstatus.getPositionstop());
                System.out.println("saomaqujian---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());
            }

            if(carstatus != null){
                if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                    List<String> listhasbox=userManService.getListHasBoxByCarId(car.getId(),carstatus.getPositionstop());
                    if(listhasbox!= null && listhasbox.size()==0){
                        if(StringUtils.isEmpty(nextstop)){
                            userManService.insertNewZhiSuoCarNextStopTcpSecond(car.getSn(),car.getId(),car.getName(),car.getHomestation());
                            System.out.println("saomaqujian---vin--"+car.getSn()+"--stop----"+car.getHomestation()+"---"+new Date());
                        }else{
                            userManService.insertNewZhiSuoCarNextStopTcpSecond(car.getSn(),car.getId(),car.getName(),nextstop);
                            System.out.println("saomaqujian---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());
                        }
                    }
                }
            }






            //根据下一站指令，获取下一个用户
            List<DeliveryOrder> listNextStopDeliveryOrder=expressManService.getListNextDeliveryOrderByNextStop(nextstop,car.getId()+"");
            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                for(DeliveryOrder nextorder:listNextStopDeliveryOrder){
                    String[] params = new String[]{nextorder.getReceiptcode()};
                    String[] phoneNumbers =new String[]{nextorder.getReceiptusermobile()};
                    //发送短信
                    //SendSmsUtil.sendSmsGetBox(params,phoneNumbers);

                    String smsstatus=userManService.getSmsStatusByCaridMobile(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"");

                    if(StringUtil.isEmpty(smsstatus) || smsstatus.equals("1")){
                        //0快递单   1零售单
                        if(nextorder.getOrdertype()==0){
                            userManService.insertNewZhiSuoCarNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",0);

                        }else{
                            userManService.insertNewZhiSuoCarSendNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",1);

                        }
                        //语音短信
                        userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);

                    }

                    //

                }
            }





            resultObj.put("error_code",0);
            resultObj.put("error_msg", "取件成功，关好仓门");
            resultObj.put("data",opendoorarray);

        }else{
            //取件码开门
            resultObj.put("error_code",1);
            resultObj.put("error_msg", "取件码开门");
            resultObj.put("data",car.getId());

        }


        responseData(resultObj.toString(), resp);
    }


    /**
     * 取件码开门
     */
    @RequestMapping(value = "/setReceiptOrderByCode")
    public void setReceiptOrderByCode(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setReceiptOrderByCode-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String carid = jsonObject.getString("carid");
        String receiptcode = jsonObject.getString("receiptcode");

        String orderid =userManService.getOrderIdByCarIdAndReceiptcode(carid,receiptcode);





        if(StringUtils.isNotEmpty(orderid)){
            Integer orderStatus=userManService.getOrderStatusByOrderId(orderid);
            if(orderStatus==3){
                resultObj.put("error_code",2);
                resultObj.put("error_msg", "该快递已被取走");
                resultObj.put("data",carid);
                return;
            }




            //打开仓门
//          //下发开箱指令
            DeliveryOrder order=userManService.getDeliveryOrderById(orderid);
            //获取TCP服务器地址
            String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");

            ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));
            List<ZhiSuoCarBox> listZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(order.getCarid()+"");
            String tcpresult= TcpUtil.openDoor(car,order,listZhiSuoCarBox,tcp_url);
            if(StringUtils.isNotEmpty(tcpresult)){
                JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
                String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
                if(tcpresultjsonerrorCode.equals("1")){
                    responseErrorData("开门失败，请再试一次", resp);
                    return;
                }
            }



            JSONObject oneboxjson=null;
            JSONArray opendoorarray=new JSONArray();
            for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
                oneboxjson=new JSONObject();
                Boolean flag=false;
                if(order.getBoxcode().equals(carbox.getName())){
                    flag=true;
                }else{
                    flag=false;
                }

                if(flag){
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","1");
                    oneboxjson.put("pos",carbox.getPos());
                }else{
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","0");
                    oneboxjson.put("pos",carbox.getPos());
                }
                opendoorarray.add(oneboxjson);
            }



            //更新箱子状态
            expressManService.updateCarBoxStatusByCode(order.getBoxcode(),order.getCarid()+"");



            userManService.updateOrderByReceiptcode(orderid,userid);


            //增加积分
            if(order.getOrdertype()==0){
                //只要零售单才会增加积分
                Integer award_integral=apiService.getAwardIntegeralByConfig("award_integral");
                //用户增加积分
                userManService.updateUserIntegralByUserId(userid,award_integral);
                //增加积分记录
                userManService.insertNewZhiSuoUserIntegralRecord(userid,order.getId(),award_integral,0,0);


            }


            //判断当前站点包裹是否取完，取完5秒直接发车
            ZhiSuoCarStatus carstatus = expressManService.getCarStatusByCarVin(car.getSn());
            //下发发车指令
            String nextstop=userManService.getNextStopByCarId(car.getId());
            String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
            if(StringUtils.isEmpty(nextstop)){
                if(carstatus==null){
                    carstatus=new ZhiSuoCarStatus();
                    carstatus.setPositionstop("");
                }
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),car.getHomestation(),stop_timeout_sec,carstatus.getPositionstop());
                System.out.println("qujianmaqujian---vin--"+car.getSn()+"--stop----"+car.getHomestation()+"---"+new Date());
            }else{
                if(carstatus==null){
                    carstatus=new ZhiSuoCarStatus();
                    carstatus.setPositionstop("");
                }
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop_timeout_sec,carstatus.getPositionstop());
                System.out.println("qujianmaqujian---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());
            }


            if(carstatus != null){
                if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                    List<String> listhasbox=userManService.getListHasBoxByCarId(car.getId(),carstatus.getPositionstop());
                    if(listhasbox!= null && listhasbox.size()==0){
                        if(StringUtils.isEmpty(nextstop)){
                            userManService.insertNewZhiSuoCarNextStopTcpSecond(car.getSn(),car.getId(),car.getName(),car.getHomestation());
                            System.out.println("qujianmaqujian---vin--"+car.getSn()+"--stop----"+car.getHomestation()+"---"+new Date());
                        }else{
                            userManService.insertNewZhiSuoCarNextStopTcpSecond(car.getSn(),car.getId(),car.getName(),nextstop);
                            System.out.println("qujianmaqujian---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());
                        }
                    }
                }
            }


            //根据下一站指令，获取下一个用户
            List<DeliveryOrder> listNextStopDeliveryOrder=expressManService.getListNextDeliveryOrderByNextStop(nextstop,order.getCarid()+"");



            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                for(DeliveryOrder nextorder:listNextStopDeliveryOrder){
                    String[] params = new String[]{nextorder.getReceiptcode()};
                    String[] phoneNumbers =new String[]{nextorder.getReceiptusermobile()};
                    //发送短信
                    //SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                    String smsstatus=userManService.getSmsStatusByCaridMobile(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"");

                    if(StringUtil.isEmpty(smsstatus) || smsstatus.equals("1")){
                        //0快递单   1零售单
                        if(nextorder.getOrdertype()==0){
                            userManService.insertNewZhiSuoCarNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",0);
                        }else{
                            userManService.insertNewZhiSuoCarSendNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",1);

                        }
                        //语音短信
                        userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);

                    }
                }
            }



            resultObj.put("error_code",0);
            resultObj.put("error_msg", "取件成功，关好仓门");
            resultObj.put("data",opendoorarray);
        }else{
            resultObj.put("error_code",1);
            resultObj.put("error_msg", "取件码错误或本车无该快递");
            resultObj.put("data","");

        }
        responseData(resultObj.toString(), resp);
    }


    /**
     * 获取用户端待预约列表 0待预约  1待取件  2已完成
     */
    @RequestMapping(value = "/getReceiptOrderListById")
    public void getDeliveryOrderDetailById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderListById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String status = jsonObject.getString("status");
        Integer page = jsonObject.getInteger("page");
        ZhiSuoUser user=apiService.getUserInfoByUserId(userid);

        if(user==null){
            responseErrorData("用户为空", resp);
            return;
        }

        //第一步，通过用户手机号，查询待派件列表中是否存在该用户订单
        List<DeliveryOrder> listDeliveryOrder=userManService.getListDeliveryOrderByReceiptMobile(user.getMobile(),status,page, Constants.PAGESIZE);
        JSONArray jsonArray=new JSONArray();
        JSONObject jo=null;
        //第二步：生成用户的待预约取件订单列表
        if(listDeliveryOrder != null &&listDeliveryOrder.size()>0){

            for(DeliveryOrder order:listDeliveryOrder){
                //通过手机号查询用户ID
                //Integer receiptuserid=apiService.getUserIdByMobile(order.getReceiptusermobile());
                jo=new JSONObject();
                ZhiSuoCar car=expressManService.getCarByCarId(order.getCarid());
                String parkareaid=expressManService.getParkareaidByCarId(car.getId());
                String parkAreaName= expressManService.getParkAreaNameById(parkareaid);
                ParkAreaBuild buildinfo=new ParkAreaBuild();
                if(order.getOrdertype()==0){
                    ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
                    if(userAddress != null){
                        buildinfo=userManService.getParkAreaBuildById(userAddress.getParkareabuildid());
                        //buildinfo=userManService.getParkAreaBuildByCode(order.getReceiptuseraddresscode());
                    }

                    if(StringUtil.isNotEmpty(order.getReceiptuserbuildid()+"")){
                        buildinfo=userManService.getParkAreaBuildById(order.getReceiptuserbuildid());
                    }

                }else{
                    buildinfo=userManService.getParkAreaBuildById(order.getReceiptuserbuildid());
                }



                jo.put("carid",car.getId());
                jo.put("carname",car.getName());
                jo.put("parkareaname",parkAreaName);
                if(buildinfo!=null){
                    jo.put("buildname",buildinfo.getName());
                }else{
                    jo.put("buildname","");
                }

                jo.put("paymnetcompany",order.getPaymentcompany());
                jo.put("paymentcode",order.getPaymentcode());
                jo.put("create_time",order.getCreate_time());
                jo.put("orderid",order.getId());
                jo.put("receiptuserorderstarttime",order.getReceiptuserorderstarttime());
                jo.put("receiptuserorderendtime",order.getReceiptuserorderendtime());
                jo.put("receipt_time",order.getReceipt_time());
                jo.put("ordertype",order.getOrdertype());
                jo.put("isovertime",order.getIsovertime());
                //0快递单   1零售单
                if(order.getOrdertype()==0){
                    ZhiSuoUser orderuser=apiService.getUserInfoByUserId(order.getUserid()+"");
                    Salesman salesman=expressManService.getSalemanByUserId(orderuser.getSalemansid());
                   if(salesman!= null){
                       jo.put("salecompany",salesman.getCompanyname());
                       jo.put("salename",salesman.getName());
                       jo.put("salemobile",salesman.getMobile());
                   }else{
                       jo.put("salecompany","");
                       jo.put("salename","");
                       jo.put("salemobile","");
                   }

                }else{
                    ZhiSuoUser orderuser=apiService.getUserInfoByUserId(order.getUserid()+"");
                    Salesman salesman=expressManService.getSellermanByUserId(orderuser.getSalemansid());
                    if(salesman!= null){
                        jo.put("salecompany",salesman.getCompanyname());
                        jo.put("salename",salesman.getName());
                        jo.put("salemobile",salesman.getMobile());
                    }else{
                        jo.put("salecompany","");
                        jo.put("salename","");
                        jo.put("salemobile","");
                    }

                }


                jsonArray.add(jo);
            }
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);


    }


    /**
     * 根据OrderId获取订单详情
     */
    @RequestMapping(value = "/getReceiptOrderDetailById")
    public void getReceiptOrderDetailById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderDetailById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        DeliveryOrder order=userManService.getDeliveryOrderById(orderid);


        JSONObject jo=new JSONObject();

        ZhiSuoCar car=expressManService.getCarByCarId(order.getCarid());
        String parkareaid=expressManService.getParkareaidByCarId(car.getId());
        String parkAreaName= expressManService.getParkAreaNameById(parkareaid);
        jo.put("carid",car.getId());
        jo.put("carname",car.getName());
        jo.put("parkareaname",parkAreaName);
        jo.put("boxname",order.getBoxcode());
        jo.put("paymentcode",order.getPaymentcode());
        jo.put("create_time",order.getCreate_time());
        jo.put("paymnetcompany",order.getPaymentcompany());
        jo.put("orderid",order.getId());
        jo.put("receiptmobile",order.getReceiptusermobile());
        jo.put("customermobile","021-60677608");
        jo.put("receiptuserorderstarttime",order.getReceiptuserorderstarttime());
        jo.put("receiptuserorderendtime",order.getReceiptuserorderendtime());
        ZhiSuoUser user=userManService.getZhiSuoUserByMobile(order.getReceiptusermobile());
        ZhiSuoUserAddress address=userManService.getZhisuoFlagUserAddressByUserId(user.getId());
        ParkAreaBuild build=null;
        if(address!= null){
           build=userManService.getParkAreaBuildById(address.getParkareabuildid());
        }else{
            build=userManService.getParkAreaBuildById(order.getReceiptuserbuildid());
        }



        ParkArea area=userManService.getParkAreaById(build.getParkareaid());
        JSONObject addressjson=new JSONObject();
        addressjson.put("addressid",address.getId());
        addressjson.put("flag",address.getFlag());
        addressjson.put("parkareaid",area.getId());
        addressjson.put("parkareaname",area.getName());
        addressjson.put("parkareabuildname",build.getName());
        addressjson.put("parkareabuildid",address.getParkareabuildid());
        jo.put("addressjson",addressjson);


        address=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
        if(address != null){
        build=userManService.getParkAreaBuildById(address.getParkareabuildid());

            area=userManService.getParkAreaById(build.getParkareaid());
            JSONObject receiptaddressjson=new JSONObject();
            receiptaddressjson.put("addressid",address.getId());
            receiptaddressjson.put("parkareaid",area.getId());
            receiptaddressjson.put("parkareaname",area.getName());
            receiptaddressjson.put("parkareabuildname",build.getName());
            receiptaddressjson.put("parkareabuildid",build.getId());
            jo.put("receiptaddressjson",receiptaddressjson);
        }else{
            jo.put("receiptaddressjson","");
        }



        ZhiSuoCarStatus carstatus=expressManService.getCarStatusByCarVin(car.getSn());
        if(carstatus!=null){
            jo.put("lng",carstatus.getPositionlon()+"");
            jo.put("lat",carstatus.getPositionlat()+"");
            jo.put("heading",carstatus.getPositionheading()+"");
            jo.put("speedvalue",carstatus.getSpeedvalue()+"");
            jo.put("speedunit",carstatus.getSpeedunit()+"");
            jo.put("remaintotal",carstatus.getRemaintotal()+"");

            if(StringUtil.isNotEmpty(carstatus.getRemaintotal())&&StringUtil.isNotEmpty(carstatus.getSpeedvalue())){

                Double remiantotal=Double.parseDouble(carstatus.getRemaintotal());
                Double speed=Double.parseDouble(carstatus.getSpeedvalue());
                if(remiantotal==0 ||speed==0){
                    jo.put("remainminute","");
                }else{
                    Integer hasminute=TimeUtil.getMinuteByDistance(remiantotal,speed);
                    jo.put("remainminute",hasminute);
                }



            }else{
                jo.put("remainminute","");
            }


            if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                if(carstatus.getPositionstop().equals(car.getHomestation())){
                    jo.put("ishomestation",1);
                }else{
                    jo.put("ishomestation",0);
                }
            }else{
                jo.put("ishomestation",0);
            }
        }else{
            jo.put("lng","121.17403723382593");
            jo.put("lat","31.147796227532314");
            jo.put("heading","");
            jo.put("speedvalue","");
            jo.put("speedunit","");
            jo.put("remaintotal","");
            jo.put("remainminute","");
            jo.put("ishomestation",0);
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jo);
        responseData(resultObj.toString(), resp);



    }




    /**
     * 根据订单ID系统分派用户收件
     */
    @RequestMapping(value = "/setReceiptOrderSysStatusById")
    public void setReceiptOrderSysStatusById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setReceiptOrderSysStatusById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        String receiptcode= RandomStringUtils.random(4, "1234567890");

        DeliveryOrder order=userManService.getDeliveryOrderById(orderid);
        ZhiSuoUser user=userManService.getZhiSuoUserByMobile(order.getReceiptusermobile());

        //获取用户默认地址
        ZhiSuoUserAddress userAddress=userManService.getZhisuoFlagUserAddressByUserId(user.getId());
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(userAddress.getParkareabuildid());


        //查看订单车辆所在区域
        String parkareaid=userManService.getParkAreaIdByCarId(order.getCarid());


        JSONObject addressjson=new JSONObject();
        if(parkareaid.equals(buildinfo.getParkareaid()+"")){

            userManService.updateReceiptOrderSysStatusById(orderid,receiptcode,buildinfo.getCode(),userAddress.getId());

        }else{

            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "该订单车辆所在区域，不在用户默认地址中，请选择手动预约");
            resultObj.put("data", orderid);
            responseData(resultObj.toString(), resp);
            return;

        }




        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        resultObj.put("data", orderid);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 根据订单ID用户预约收件时间
     */
    @RequestMapping(value = "/setReceiptOrderOrderTimeStatusById")
    public void setReceiptOrderOrderTimeStatusById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setReceiptOrderOrderTimeStatusById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        String addressid = jsonObject.getString("addressid");

        String receiptuserorderstarttime = jsonObject.getString("receiptuserorderstarttime");

        String receiptuserorderendtime = jsonObject.getString("receiptuserorderendtime");

        String receiptcode= RandomStringUtils.random(4, "1234567890");

        //查询当前时间段有几单
        List<Integer> count=userManService.getDeliveryOrderCountByOrderTime(receiptuserorderstarttime,receiptuserorderendtime);
        if(count != null){
            if(count.size()>=5){
                responseErrorData("该时间段预约订单超量，请重新选择时间段", resp);
                return;
            }
        }


//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //获取当前时间
//        String nowminutes = DateUtil.getMinute(sdf.format(new Date()));
//        Integer intnowm = Integer.parseInt(nowminutes);
//        if (intnowm >= 55) {
//            resultObj.put("error_code", 1);
//            resultObj.put("error_msg", "当前时间不可预约");
//            resultObj.put("data", "");
//            responseData(resultObj.toString(), resp);
//            return;
//        }



        ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(Integer.parseInt(addressid));
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(userAddress.getParkareabuildid());

        DeliveryOrder order=userManService.getDeliveryOrderById(orderid);
        String parkareaid=userManService.getParkAreaIdByCarId(order.getCarid());
        if(parkareaid.equals(buildinfo.getParkareaid()+"")){
            userManService.updateReceiptOrderTimeStatusById(orderid,addressid,receiptuserorderstarttime,receiptuserorderendtime,receiptcode,buildinfo.getCode());

        }else{
            responseErrorData("预约失败", resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        resultObj.put("data", orderid);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 根据用户ID获取地址列表
     */
    @RequestMapping(value = "/getListUserAddressByUserId")
    public void getListUserAddressByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getListUserAddressByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");

        List<ZhiSuoUserAddress> listZhiSuoUserAddress=userManService.getListUserAddressByUserId(userid);

        JSONArray jsonArray=new JSONArray();
        JSONObject jo=null;
        for(ZhiSuoUserAddress address:listZhiSuoUserAddress){
            //ParkAreaBuild
            jo=new JSONObject();
            ParkAreaBuild build=userManService.getParkAreaBuildById(address.getParkareabuildid());
            ParkArea area=userManService.getParkAreaById(build.getParkareaid());
            jo.put("addressid",address.getId());
            jo.put("flag",address.getFlag());
            jo.put("parkareaname",area.getName());
            jo.put("parkareaid",area.getId());
            jo.put("parkareabuildname",build.getName());
            jo.put("parkareabuildid",address.getParkareabuildid());
            jsonArray.add(jo);
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 添加地址
     */
    @RequestMapping(value = "/addUserAddress")
    public void setMobileByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("addUserAddress-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String parkareabuildid = jsonObject.getString("parkareabuildid");
        String flag = jsonObject.getString("flag");
        if(flag.equals("1")){
            apiService.updateUserAddressFlag(userid);
        }
        //查询地址是否存在库中
        String useraddressid = apiService.getUserAddressIdByUserIdAndPrkareabuildid(userid, parkareabuildid);

        if (StringUtils.isEmpty(useraddressid)) {
            apiService.insertNewUserAddrss(userid, parkareabuildid,flag);
        }else{
            apiService.updateUserAddressFlagStatus(useraddressid,flag);
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        responseData(resultObj.toString(), resp);

    }



    /**
     * 删除地址
     */
    @RequestMapping(value = "/deleteUserAddress")
    public void deleteUserAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("deleteUserAddress-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String addressid = jsonObject.getString("addressid");

        apiService.deleteUserAddressById(addressid);


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        responseData(resultObj.toString(), resp);

    }



    /**
     * 编辑地址
     */
    @RequestMapping(value = "/updateUserAddress")
    public void updateUserAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("updateUserAddress-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String addressid = jsonObject.getString("addressid");
        String parkareabuildid = jsonObject.getString("parkareabuildid");
        String flag = jsonObject.getString("flag");

        ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(Integer.parseInt(addressid));

        if(flag.equals("1")){
            apiService.updateUserAddressFlag(userAddress.getUserid()+"");
        }

        apiService.updateUserAddressIdByUserIdAndPrkareabuildid(addressid, parkareabuildid,flag);


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "操作成功");
        responseData(resultObj.toString(), resp);

    }





    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
